<style scoped>
.fileSpace {
  height: 100%;
}
.folderContent {
  overflow-y: auto;
  padding: 5px;
  margin: 3px;
}

.resourceTitle {
  font-size: 18px;
  height: 20px;
  line-height: 20px;
}

.resourceBtnDiv {
  display: flex;
  align-items: center;
  height: 20px;
  padding: 5px;
}

.fileBtn {
  margin: 0px 3px;
}

.itemIcon {
  margin-right: 5px;
}

.fileItemName {
  width: 35%;
  margin-right: 5%;
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: top;
  cursor: pointer;
  overflow: hidden;
}

.fileItemSize {
  width: 10%;
  margin-right: 5%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  height: 16px;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.demo-spin-col {
  height: 100px;
  position: relative;
  /* border: 1px solid #eee; */
}

/* .personalFileLabel {
  width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
} */

.personalFileDes {
  display: inline-block;
  margin: 0 5px;
  width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.fileBtnHoverBlue:hover {
  background-color: #2db7f5;
  color: white;
}

.fileBtnHoverGreen:hover {
  background-color: #19be6b;
  color: white;
}

.fileBtnHoverOrange:hover {
  background-color: #ff9900;
  color: white;
}

.fileBtnHoverRed:hover {
  background-color: #ed4014;
  color: white;
}

.fileBtnHoverGray:hover {
  background-color: #808695;
  color: white;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

.previewBox {
  height: 63vh;
  margin-left: 1%;
}
.previewBox >>> .__rail-is-horizontal {
  display: none;
}
.uploader-example {
  width: 97%;
  padding: 5px;
  margin: 10px 0 10px 20px;
  font-size: 12px;
}

.uploader-example .uploader-btn {
  margin-right: 4px;
}

.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
<template>
  <div class="fileSpace">
    <Card :padding="1" dis-hover style="height:95%;overflow: auto;">
      
      <div slot="extra" class="resourceBtnDiv" v-show="userRole == 'admin'"></div>
 

      <!-- 内容 -->
      <div class="folderContent">
        <Card v-if="folderStack.length > 0" :padding="1" dis-hover>
          <div style="display: flex; align-items: center">
            <div style="min-width: 60px" v-show="currentFolder.files.length > 0">
              <!--              indeterminate 表示有选中内容
                                checkAll则是全选
              -->
              <Checkbox
                :indeterminate="indeterminate"
                :value="checkAll"
                @click.prevent.native="handleCheckAll"
                v-show="currentFolder.files.length > 0"
                style="align-items: center"
                >全选
              </Checkbox>
            </div>
            <div style="margin-left: 3px">
              <Breadcrumb>
                <BreadcrumbItem
                  v-for="(folder, index) in folderStack"
                  :key="folder.uid"
                  @click.native="switchFolder(folder, index)"
                  style="cursor: pointer"
                >
                  <span v-if="folder.uid == activityInfo.aid"
                    ><Icon type="md-folder" style="color: #2d8cf0"
                  /></span>
                  <span v-else style="color: #2d8cf0">{{ folder.name }}</span>
                </BreadcrumbItem>
              </Breadcrumb>
            </div>
            <Divider type="vertical" style="margin-left: 20px" />
            <div style="flex: 1; margin-left: 10px">
              <Tooltip content="Back" placement="bottom" class="fileBtn">
                <Icon
                  type="md-arrow-round-back"
                  @click="backforeFolder"
                  style="cursor: pointer; color: #08ab2b"
                />
              </Tooltip>
              <Tooltip content="New folder" placement="bottom" class="fileBtn">
                <Icon
                  type="ios-folder"
                  @click="addFolderModalShow"
                  style="cursor: pointer; color: #f9c245"
                />
              </Tooltip>
            </div>
            <div
              style="align-items: flex-end; margin-right: 15px"
              v-if="userRole != 'visitor'"
            >
              <!-- <Tooltip content="Download" placement="bottom" class="fileBtn">
                <Button
                  @click="downloadSelectFile"
                  v-show="currentFolder.files.length > 0"
                  shape="circle"
                  icon="md-cloud-download"
                  class="fileBtnHoverGray"
                  v-if="userRole != 'visitor'"
                ></Button>
              </Tooltip> -->
              <Tooltip content="快速创建文件夹" placement="bottom" class="fileBtn">
                <Button
                  @click="flashModalShow"
                  shape="circle"
                  icon="md-flash"
                  class="fileBtnHoverBlue"
                  v-if="
                    (userInfo.role == 'admin' || userInfo.role == 'teacher') &&
                    studentUpload == 'true'
                  "
                ></Button>
              </Tooltip>
              <Tooltip content="上传文件" placement="bottom" class="fileBtn">
                <Button
                  @click="uploadModalShow"
                  shape="circle"
                  icon="md-cloud-upload"
                  class="fileBtnHoverGreen"
                  v-if="
                    userInfo.role == 'admin' ||
                    userInfo.role == 'teacher' ||
                    (studentUpload == 'true' && folderLock == false)
                  "
                ></Button>
              </Tooltip>
              <!-- <Tooltip content="上传大文件" placement="bottom" class="fileBtn">
                <Button
                  @click="uploadModalBigFileShow"
                  shape="circle"
                  icon="md-cloud-upload"
                  class="fileBtnHoverGreen"
                  v-if="
                    userInfo.role == 'admin' ||
                    userInfo.role == 'teacher' ||
                    (studentUpload == 'true' && folderLock == false)
                  "
                ></Button>
              </Tooltip> -->
              <Tooltip  v-if="folderStack.length == 1" content="缩略图展示" placement="bottom" class="fileBtn">
                <Button
                  @click="thumbnailShow=true,getResList()"
                  shape="circle"
                  icon="md-grid"
                  class="fileBtnHoverBlue"
                  v-if="
                    userInfo.role == 'admin' ||
                    userInfo.role == 'teacher' ||
                    (studentUpload == 'true' && folderLock == false)
                  "
                ></Button>
              </Tooltip>
              <Tooltip v-if="folderStack.length == 1" content="列表展示" placement="bottom" class="fileBtn">
                <Button
                  @click="thumbnailShow=false,getAllResList()"
                  shape="circle"
                  icon="ios-list-box-outline"
                  class="fileBtnHoverBlue"
                  v-if="
                    userInfo.role == 'admin' ||
                    userInfo.role == 'teacher' ||
                    (studentUpload == 'true' && folderLock == false)
                  "
                >
               </Button>
              </Tooltip>
            </div>
          </div>
        </Card>
        <div
          v-if="(currentFolder.folders.length > 0 || currentFolder.files.length > 0)&& thumbnailShow  "
          style="height: 100%"
        >
          <el-row style="height: 30%">
            <!-- 文件夹 -->
            <el-col :span="4" v-for="item in currentFolder.folders" :key="item.id">
              <Dropdown
                :padding="1"
                trigger="contextMenu"
                style="margin-left: 7px; margin-top: 10px"
                placement="right"
              >
                <Card class="folderCard">
                  <el-row style="height: 30%">
                    <el-col :span="5"
                      >&nbsp;
                      <div
                        style="margin: 4px; float: inherit; cursor: pointer"
                        v-if="item.folder == false"
                      >
                        <i style="font-size: 16px; color: #1b7cde"></i>
                      </div>
                    </el-col>
                    <el-col :span="15" >
                      <img
                        class="fileImg"
                        src="@/assets/images/folder.png"
                        align="middle"
                        ref="folderImg"
                        @dblclick="enterFolder(item)"
                        style="
                          height: 100%;
                          width: 100%;
                          object-fit: contain;
                          cursor: pointer;
                        "
                      />
                    </el-col>
                    <el-col :span="4"> </el-col>
                  </el-row>
                  <el-row
                    type="flex"
                    justify="center"
                    v-if="item"
                    class="fileName"
                    @click.native="enterFolder(item)"
                    style="cursor: pointer"
                  >
                    <div>
                      <p
                        style="
                          text-align: center;
                          word-break: break-all;
                          width: 10rem;
                          overflow: hidden;
                          text-overflow: ellipsis;
                          white-space: nowrap;
                        "
                        v-if="item"
                      >
                        {{ item.name.toString() }}
                      </p>
                    </div>

                    <p v-if="item.suffix">.</p>
                    <p v-if="item.suffix">{{ item.suffix }}</p>
                  </el-row>
                </Card>
               <div>
               </div>
                <DropdownMenu slot="list">
                  <DropdownItem @click.native="renameFolderModalShow(folder)"
                    >Rename</DropdownItem
                  >
                  <!-- <DropdownItem @click.native="lessonInfoModal(item)">详细信息</DropdownItem> -->
                  <DropdownItem
                    style="color: #ed4014"
                    @click.native="deleteFolder(folder)"
                    v-show="userInfo.role == 'admin'"
                    >删除</DropdownItem
                  >
                </DropdownMenu>
              </Dropdown>
            </el-col>
            <!-- 文件 -->
            <el-col :span="4" v-for="file in currentFolder.files" :key="file.id">
              <CheckboxGroup v-model="chooseFilesArray" @on-change="checkAllGroupChange">
                <Dropdown
                  :padding="1"
                  trigger="contextMenu"
                  style="margin-left: 7px; margin-top: 10px"
                  placement="right"
                >
                  <Card
                    :padding="5"
                    style="margin-left: 7px; margin-top: 10px"
                    :style="{
                      height: folderCardHeight + 3 + 'px',
                      width: folderCardWidth + 'px',
                    }"
                  >
                    <el-row style="height: 30%">
                      <el-col :span="5"
                        >&nbsp;

                        <div
                          style="cursor: pointer; position: absolute; top: 5px; left: 5px"
                        >
                          <Checkbox :label="file.id" style="font-size: 16px"
                            >&nbsp;</Checkbox
                          >
                        </div>
                      </el-col>
                      <el-col
                        :span="15"
                        style="height: 100%; margin: 5% 0"
                        :style="{
                          height: boxImgSize - 10 + 'px',
                          width: boxImgSize + 'px',
                        }"
                      >
                        <img
                          v-if="file.suffix == 'zip'"
                          :id="file.id"
                          class="fileImg"
                          src="@/assets/images/zip.png"
                          align="middle"
                          alt="图片"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                        <img
                          v-else-if="file.suffix == 'txt'"
                          :id="file.id"
                          class="fileImg"
                          src="@/assets/images/paper.png"
                          align="middle"
                          alt="图片"
                          @dblclick="getFileInfo(file)"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                        <img
                          v-else-if="file.suffix == 'pdf'"
                          :id="file.id"
                          class="fileImg"
                          src="@/assets/images/pdf.png"
                          align="middle"
                          alt="图片"
                          @dblclick="getFileInfo(file)"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                        <img
                          v-else-if="file.suffix == 'mp4'"
                          :id="file.id"
                          class="fileImg"
                          src="@/assets/images/video.png"
                          align="middle"
                          alt="图片"
                          @dblclick="getFileInfo(file)"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                        <img
                          v-else-if="file.suffix == 'xls'"
                          :id="file.id"
                          class="fileImg"
                          src="@/assets/images/excel.jpg"
                          align="middle"
                          alt="图片"
                          @dblclick="getFileInfo(file)"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                        <img
                          v-else
                          class="fileImg"
                          :id="file.id"
                          src="@/assets/images/document.png"
                          align="middle"
                          alt="图片"
                          @dblclick="getFileInfo(file)"
                          style="
                            height: 100%;
                            width: 100%;
                            object-fit: contain;
                            cursor: pointer;
                          "
                        />
                      </el-col>
                    </el-row>
                    <el-row
                      type="flex"
                      justify="center"
                      v-if="file"
                      class="fileName"
                      @click.native="getFileInfo(file)"
                      style="cursor: pointer"
                    >
                      <p
                        class="overEllipsis"
                        :title="file.name"
                        style="
                          text-align: center;
                          word-break: break-all;
                          overflow: hidden;
                          text-overflow: ellipsis;
                          white-space: nowrap;
                        "
                        v-if="file"
                      >
                        {{ file.name }}
                      </p>
                      <p v-if="file.suffix">.</p>
                      <p v-if="file.suffix">{{ file.suffix }}</p>
                    </el-row>
                  </Card>

                  <DropdownMenu slot="list"  >
                    <DropdownItem @click.native="fileDownload(file)"
                      >下载该文件</DropdownItem
                    >
                    <!-- <DropdownItem @click.native="lessonInfoModal(item)">详细信息</DropdownItem> -->
                    <DropdownItem
                      @click.native="fileEditModelShow(file)"
                      v-show="userInfo.role == 'admin' || userInfo.role == 'teacher'"
                      >编辑</DropdownItem
                    >
                    <DropdownItem
                      @click.native="fileDelete(file)"
                      v-show="userInfo.role == 'admin' || userInfo.role == 'teacher'"
                      >删除</DropdownItem
                    >
                  </DropdownMenu>
                </Dropdown>
              </CheckboxGroup>
            </el-col>
          </el-row>
        </div>
        <div
        
          v-if="
            (currentFolder.folders.length > 0 || currentFolder.files.length > 0)&& thumbnailShow ==false
          "
        >
          <vue-scroll :ops="ops" :style="{ height: contentHeight -8 + 'px' }">
            <Card
              v-for="(folder, index) in currentFolder.folders"
              :key="index"
              :padding="5"
            >
              <div>
                <Icon type="ios-folder-open" class="itemIcon" size="25" />
                <a
                  @click="enterFolder(folder)"
                  class="fileItemName"
                  :title="folder.name"
                  >{{ folder.name }}</a
                >

                <!--                文件夹结构-->
                <div style="float: right">
                  <Button
                    @click="renameFolderModalShow(folder)"
                    class="fileBtnHoverBlue"
                    shape="circle"
                    icon="ios-create"
                    title="Rename"
                    size="small"
                    type="text"
                    v-if="
                      (userInfo.role == 'admin' ||
                        userInfo.role == 'teacher') &&
                      folder.fromClassTask != 'true'
                    "
                  ></Button>
                  <Button
                    @click="deleteFolder(folder)"
                    class="fileBtnHoverRed"
                    shape="circle"
                    icon="ios-trash"
                    title="Delete"
                    size="small"
                    style="margin-left: 5px"
                    type="text"
                    v-if="
                      (userInfo.role == 'admin' ||
                        userInfo.role == 'teacher') &&
                      folder.fromClassTask != 'true'
                    "
                  ></Button>
                </div>
              </div>
            </Card>
            <CheckboxGroup
              v-model="chooseFilesArray"
              @on-change="checkAllGroupChange"
            >
              <Card
                v-for="file in currentFolder.files"
                :key="file.id"
                :padding="5"
              >
                <Checkbox :label="file.id">&nbsp;</Checkbox>
                <Icon
                  v-if="file.type === 'data'"
                  type="ios-podium-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'image'"
                  type="ios-image-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'paper'"
                  type="ios-paper-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'document'"
                  type="ios-document-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'model'"
                  type="ios-construct-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'video'"
                  type="ios-videocam-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else
                  type="ios-create-outline"
                  class="itemIcon"
                  size="25"
                />
                <span
                  @click="getFileInfo(file)"
                  class="fileItemName"
                  :title="file.name"
                  >{{ file.name + "." + file.suffix }}</span
                >
                <span class="fileItemSize">{{
                  file.fileSize | filterSizeType
                }}</span>
                <span style="width: 20%; margin-right: 5%">{{
                  file.createTime | filterTimeStyle
                }}</span>

                <!--                使用资源-->
                <div style="float: right">
                  <template
                    v-if="
                      userInfo.role == 'admin' ||
                      userInfo.role == 'teacher' ||
                      file.uploaderRole == 'admin' ||
                      file.uploaderRole == 'teacher' ||
                      file.uploaderId == 'admin' ||
                      (file.uploaderId == userInfo.userId &&
                        folderLock == false)
                    "
                  >
                    <Button
                      @click="fileDownload(file)"
                      shape="circle"
                      icon="ios-cloud-download"
                      title="Download"
                      size="small"
                      class="fileBtnHoverGray"
                      type="text"
                    ></Button>
                  </template>

                  <!--                  管理资源-->
                  <template
                    v-if="
                      userInfo.role == 'admin' ||
                      userInfo.role == 'teacher' ||
                      (file.uploaderId == userInfo.userId &&
                        folderLock == false)
                    "
                  >
                    <Button
                      @click="fileEditModelShow(file)"
                      shape="circle"
                      icon="md-create"
                      title="Edit info"
                      size="small"
                      class="fileBtnHoverBlue"
                      type="text"
                    ></Button>
                    <Button
                      @click="fileDelete(file)"
                      shape="circle"
                      icon="ios-trash"
                      title="Remove"
                      size="small"
                      class="fileBtnHoverRed"
                      type="text"
                    ></Button>
                  </template>
                </div>
              </Card>
            </CheckboxGroup>
          </vue-scroll>
        </div>

        <div v-if="currentFolder.folders.length < 1 && currentFolder.files.length < 1" style="text-align: center">
          <div style="color: lightgray; font-size: 2em; font-weight: bold">
            No file or folder
          </div>
        </div>  
        
      </div>
    </Card>
    <div v-if="thumbnailShow" style="display: flex; justify-content: center; margin-top:8px">
      <Page
        :total="dataCount"
        :page-size="pageSize"
        :current="currentPage"
        show-total
        @on-change="changepage"
        show-elevator
      />
    </div>
    <Modal
      v-model="renameFolderModal"
      title="文件夹重命名"
      ok-text="Assure"
      cancel-text="Cancel"
    >
      <Form
        ref="renameValidate"
        :model="renameValidate"
        :rules="renameRuleValidate"
        :label-width="80"
      >
        <FormItem label="新名称" prop="newName">
          <Input v-model="renameValidate.newName" placeholder="输入新的文件夹名..." />
          <input type="text" style="display: none" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="renameFolderModal = false">取消</Button>
        <Button type="success" @click="renameFolder('renameValidate')">重命名 </Button>
      </div>
    </Modal>
    <Modal v-model="newFolderModal" title="创建文件夹">
      <Form
        ref="newValidate"
        :model="newValidate"
        :rules="newRuleValidate"
        :label-width="80"
        @submit.native.prevent
      >
        <FormItem label="设置名称" prop="setName">
          <Input v-model="newValidate.setName" :rows="4" placeholder="输入文件夹名..." />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="newFolderModal = false">Cancel</Button>
        <Button type="success" @click="addFolder('newValidate')">New</Button>
      </div>
    </Modal>

    <Modal v-model="uploadModal" title="上传文件" width="600">
      <Form
        ref="uploadValidate"
        :model="uploadValidate"
        :rules="uploadRuleValidate"
        :label-width="100"
        inline
      >
        <FormItem label="资源描述" prop="description" style="width: 90%">
          <Input type="textarea" :rows="3" v-model="uploadValidate.description" />
        </FormItem>
      </Form>
      <Upload
        :max-size="1024 * 1024"
        multiple
        type="drag"
        :before-upload="gatherFile"
        action="-"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>
            点击或拖拽文件上传 ( 文件大小不超过
            <span style="color: red">2GB</span>)
          </p>
        </div>
      </Upload>
      <div style="padding: 0 10px 0 10px; max-height: 200px; overflow-y: auto">
        <ul v-for="(list, index) in toUploadFiles" :key="index">
          <li style="display: flex">
            文件名:
            <span style="font-size: 10px; margin: 0 5px 0 5px"
              >{{ list.name }} ( {{ list.fileSize }} )</span
            >
            <Icon
              type="ios-close"
              size="20"
              @click="delFileList(index)"
              style="display: flex; justify-content: flex-end; cursor: pointer"
            ></Icon>
          </li>
        </ul>
      </div>
      <div slot="footer">
        <Button @click="uploadModal = false">取消</Button>
        <Button type="success" @click="folderUpload('uploadValidate')">上传 </Button>
      </div>
    </Modal>
    <Modal v-model="flashModal" title="快速创建成员文件夹" width="600">
      <!-- <div style="width:80% ;margin: auto; margin-bottom: 10px;">
        <span>文件夹命名：</span>
        <Input v-model="value" placeholder="请输入..." style="width: 300px"></Input>
      </div> -->
      <div style="width: 80%; margin: auto; margin-bottom: 7px">
        <span>成员列表：</span>
      </div>
      <div style="width: 80%; margin: auto; height: 40vh">
        <Transfer
          :data="flashMemberList"
          :target-keys="flashMemberTargetKeys"
          :render-format="flashMemberRender"
          @on-change="flashMemberHandleChange"
          :list-style="listStyle"
          v-if="getParticipantsFinished"
        ></Transfer>
      </div>
      <div slot="footer">
        <Button @click="flashModal = false">取消</Button>
        <Button type="success" @click="flashMemberUpload()">快速创建 </Button>
      </div>
    </Modal>
    <Modal
      v-model="progressModalShow"
      title="Upload Progress"
      :mask-closable="false"
      :closable="false"
    >
      <Progress :percent="uploadProgress"></Progress>
      <div slot="footer"></div>
    </Modal>
    <Modal v-model="fileInfoModal" title="文件详细信息">
      <Table
        :columns="selectedFileColumns"
        :data="selectedFileData"
        stripe
        border
        :show-header="false"
      ></Table>
      <div slot="footer">
        <Button
          type="warning"
          @click="filePreview()"
          v-if="
            userInfo.role == 'admin' ||
            userInfo.role == 'teacher' ||
            selectInfo.uploaderId == 'admin' ||
            selectInfo.uploaderId == userInfo.userId ||
            selectInfo.uploaderRole == 'admin' ||
            selectInfo.uploaderRole == 'teacher' ||
            folderLock == true
          "
          >查看</Button
        >
        <Button type="primary" @click="fileInfoModal = false">OK</Button>
      </div>
    </Modal>
    <Modal
      v-model="shareModal"
      title="Share file from personal center"
      width="600"
      :mask-closable="false"
    >
      <div>
        <vue-scroll :ops="ops" style="height: 300px">
          <CheckboxGroup v-model="selectedFilesToShare">
            <Card dis-hover v-for="file in userResourceList" :key="file.index">
              <Checkbox
                :label="file.id"
                class="personalFileLabel"
                :title="file.name"
                v-if="canBeShare(file.id)"
              >
                <Icon
                  v-if="file.type === 'data'"
                  type="ios-podium-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'image'"
                  type="ios-image-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'paper'"
                  type="ios-paper-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'document'"
                  type="ios-document-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'model'"
                  type="ios-construct-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'video'"
                  type="ios-videocam-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon v-else type="ios-create-outline" class="itemIcon" size="25" />
                <p
                  style="
                    display: inline-block;
                    vertical-align: top;
                    width: 100px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                >
                  <strong>{{ file.name }}</strong>
                </p>
              </Checkbox>
              <Checkbox
                :label="file.uid"
                class="personalFileLabel"
                :title="file.name"
                disabled
                v-else
              >
                <Icon
                  v-if="file.type === 'data'"
                  type="ios-podium-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'image'"
                  type="ios-image-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'paper'"
                  type="ios-paper-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'document'"
                  type="ios-document-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'model'"
                  type="ios-construct-outline"
                  class="itemIcon"
                  size="25"
                />
                <Icon
                  v-else-if="file.type === 'video'"
                  type="ios-videocam-outline"
                  class="itemIcon"
                  size="25"
                />
                <p
                  style="
                    display: inline-block;
                    vertical-align: top;
                    width: 100px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                >
                  <strong>{{ file.name }}</strong>
                </p>
              </Checkbox>
              <p
                :title="file.description"
                style="
                  display: inline-block;
                  vertical-align: top;
                  width: 200px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  margin-left: 50px;
                "
              >
                {{ file.description }}
              </p>
              <span style="display: inline-block; vertical-align: top; float: right">{{
                file.fileSize | filterSizeType
              }}</span>
            </Card>
          </CheckboxGroup>
        </vue-scroll>
      </div>
      <div slot="footer" style="display: inline-block">
        <i-button type="primary" @click="shareFile()" style="float: right"
          >Submit
        </i-button>
        <i-button @click="closeshareModel()" style="float: right; margin-right: 15px"
          >Cancel
        </i-button>
      </div>
    </Modal>
    <Modal v-model="editFileModel" title="修改资源信息" width="600">
      <Form
        ref="editFileValidate"
        :model="editFileValidate"
        :rules="editFileRuleValidate"
        :label-width="100"
        inline
      >
        <!-- <FormItem label="资源类型" prop="type">
          <RadioGroup v-model="editFileValidate.type">
            <Radio label="data"></Radio>
            <Radio label="paper"></Radio>
            <Radio label="document"></Radio>
            <Radio label="model"></Radio>
            <Radio label="image"></Radio>
            <Radio label="video"></Radio>
            <Radio label="others"></Radio>
          </RadioGroup>
        </FormItem> -->
        <FormItem label="资源名称" prop="name" style="width: 100%">
          <Input
            v-model="editFileValidate.name"
            placeholder="Enter the name for file..."
          />
          <input type="text" style="display: none" />
        </FormItem>
        <FormItem label="资源描述" prop="description" style="width: 100%">
          <Input type="textarea" :rows="3" v-model="editFileValidate.description" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editFileModel = false">取消</Button>
        <Button type="success" @click="editFileInfo('editFileValidate')"
          >确定修改
        </Button>
      </div>
    </Modal>
    <Modal v-model="copyFileModal" title="Copy file to personal center" width="500">
      <RadioGroup v-model="copyFilePrivacy">
        <Radio label="public">Public</Radio>
        <Radio label="private">Private</Radio>
      </RadioGroup>
      <div slot="footer">
        <Button @click="copyFileModal = false">Cancel</Button>
        <Button type="success" @click="copyFileToCenter">Copy</Button>
      </div>
    </Modal>
    <Modal
      v-model="filePreviewModal"
      :title="selectInfo.name"
      :width="1100"
      :mask-closable="false"
      @on-cancel="closeFilePreview()"
      class="previewBoxModal"
    >
      <div class="previewBox" style="display: flex">
        <vue-scroll :ops="scrollOps" style="height: 100%; width: 1100px">
          <iframe
            v-if="previewType == 'normal'"
            :src="previewUrl"
            frameborder="0"
            style="height: 60vh; width: 1060px"
          ></iframe>
          <video-player
            class="video-player vjs-custom-skin"
            ref="videoPlayer"
            :playsinline="true"
            :options="playerOptions"
            style="height: 60vh; width: 1060px"
            v-if="videoUrlFinished && previewType == 'video'"
          >
          </video-player>
          <div
            v-if="txtReloadFinished && previewType == 'txt'"
            style="height: 60vh; width: 1060px; font-size: 18px"
          >
            {{ previewUrl }}
          </div>
          <!-- <div
            v-if="previewType == 'office'"
            style="height: 60vh; width: 860px; font-size: 18px"
          >
            暂不支持Office文件预览，请下载后查看
          </div> -->
          <iframe
            v-if="previewType == 'office'"
            :src="previewUrl"
            frameborder="0"
            style="height: 60vh; width: 1060px"
          >
          </iframe>
        </vue-scroll>
        <div style="width: 250px; height: 51vh" v-if="scoreModal">
          <h3 style="margin-top: 30px">作业批阅</h3>
          <Input
            v-model="scoreReview"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 12 }"
            placeholder="请输入评阅意见..."
            style="margin-top: 10px; width: 230px"
          ></Input>
          <h3 style="margin-top: 20px">作业得分</h3>
          <Input
            v-model="scoreLevel"
            type="text"
            placeholder="请输入评阅分数..."
            style="margin-top: 10px; width: 230px"
          ></Input>
        </div>
      </div>
      <div slot="footer">
        <Button
          type="warning"
          style="float: left"
          v-if="
            (userInfo.role == 'admin' || userInfo.role == 'teacher') &&
            (selectInfo.uploaderRole != 'admin' ||
              selectInfo.uploaderRole != 'teacher') &&
            studentUpload == 'true'
          "
          @click="showScoreModal()"
          >评阅</Button
        >
        <span
          v-if="
            (userInfo.role == 'admin' || userInfo.role == 'teacher') &&
            (selectInfo.uploaderRole != 'admin' ||
              selectInfo.uploaderRole != 'teacher') &&
            studentUpload == 'true' &&
            selectInfo.scoreLevel != ''
          "
          style="float: left; margin-left: 10px; line-height: 32px"
          >已评阅，得分<strong style="color: #ff3300; margin: 0 5px">{{
            selectInfo.scoreLevel
          }}</strong
          >分</span
        >
        <Button type="primary" @click="closeFilePreview()">OK</Button>
      </div>
    </Modal>
    <!-- <Modal
      v-model="uploadModalBigFile"
      title="上传资源"
      @on-ok="submitFile()"
      ok-text="Submit"
      cancel-text="Cancel"
      :mask-closable="false"
      width="600px"
    >
      <br />
      <div style="display: flex; align-items: center; justify-content: center">
        <span style="width: 20%; text-align: center">资源描述：</span>
        <Input
          type="textarea"
          :rows="2"
          v-model="fileDescription"
          style="width: 80%; float: left"
        />
      </div>
      <div style="width: 100%">
        <uploader
          :options="uploaderOptions"
          :autoStart="true"
          :fileStatusText="{
            success: '上传成功',
            error: '上传失败',
            uploading: '正在上传',
            paused: '暂停上传',
            waiting: '等待上传',
          }"
          @file-success="onFileSuccess"
          @file-added="fileAdded"
          @file-error="onFileError"
          class="uploader-example"
        >
          <uploader-unsupport></uploader-unsupport>
          <uploader-drop>
            <uploader-btn :attrs="attrs" single>上传</uploader-btn>
          </uploader-drop>
          <uploader-list></uploader-list>
        </uploader>
      </div>
      <div style="padding: 0 10px 0 10px; max-height: 200px; overflow-y: auto">
        <ul v-for="(list, index) in toUploadFiles" :key="index">
          <li style="display: flex">
            File name:
            <span style="font-size: 10px; margin: 0 5px 0 5px"
              >{{ list.name }} ( {{ list.fileSize }} )</span
            >
            <Icon
              type="ios-close"
              size="20"
              @click="delFileList(index)"
              style="display: flex; justify-content: flex-end; cursor: pointer"
            ></Icon>
          </li>
        </ul>
      </div>
    </Modal> -->
    <!-- <login-modal
      :tempLoginModal="tempLoginModal"
      @changeLoginModal="changeLoginModal"
    ></login-modal> -->
  </div>
</template>
<script>
import loginModal from "../user/userState/loginModal.vue";
import { get, post, del, put } from "@/axios";
import { videoPlayer } from "vue-video-player";
import "video.js/dist/video-js.css";
export default {
  components: {
    loginModal,
    videoPlayer,
  },
  props: ["activityInfo"],
  data() {
    return {
      scrollOps: {
        bar: {
          background: "#808080",
          keepShow: true,
          size: "8px",
        },
        rail: {
          background: "#d7d7d7",
          opacity: 0.8,
          size: "10px",
        },
      },
      userInfo: {},
      userRole: "visitor",
      thumbnailShow: true,//缩略图显示
      boxImgSize: 0,
      folderCardHeight: 0,
      folderCardWidth: 0,
      dataCount: 0,
      pageSize: 18,
      currentPage: 1,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。

        sources: [
          {
            type: "video/mp4", // 类型
            src: "", // url地址
          },
        ],
        poster: "", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
        replyTarget: "",
      },
      videoUrlFinished: false,
      currentFolder: {
        folders: [],
        files: [],
      },
      classId: "",
      pathStr: "",
      folderStack: [{ uid: 0, name: "Home" }],
      folderIdStack: [],
      newFolderModal: false,
      newValidate: {
        setName: "",
      },
      newRuleValidate: {
        setName: [
          {
            required: true,
            message: "The name can't be null.",
            trigger: "blur",
          },
        ],
      },
      renameForeInfo: {},
      renameFolderModal: false,
      renameValidate: {
        newName: "",
      },
      renameRuleValidate: {
        newName: [
          {
            required: true,
            message: "The name can't be null.",
            trigger: "blur",
          },
        ],
      },
      editFileValidate: {
        name: "",
        type: "",
        description: "",
        format: "",
        scale: "",
        reference: "",
        unit: "",
        concept: "",
      },
      editFileRuleValidate: {
        name: [
          {
            required: true,
            message: "file description cannot be empty",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: false,
            message: "file description cannot be empty",
            trigger: "blur",
          },
        ],
      },
      // uploaderOptions: {
      //   target: "/visualResourceLibrary/res/bigFile/", //上传地址
      //   chunkSize: 5 * 1024 * 1024,
      //   testChunks: false,
      //   headers: {
      //     //设置header
      //     Authorization: JSON.parse(localStorage.getItem("userInfo")).token,
      //   },
      //   singleFile: true,
      //   query: {
      //     //传参,没有可以不传
      //     // folderId: this.folderIdStack[0],
      //     // type: this.fileType,
      //   },
      // },
      // attrs: {
      //   accept: "*", //接受文件类型
      // },
      // fileDescription:"",
      uploadModal: false,
      // uploadModalBigFile: false,
      uploadValidate: {
        type: "data",
        description: "",
      },
      flashModal: false,
      flashMemberList: [],
      flashMemberTargetKeys: [],
      listStyle: {
        height: "40vh",
      },
      uploadRuleValidate: {
        // type: [
        //   {
        //     required: true,
        //     message: "file type cannot be empty",
        //     trigger: "blur",
        //   },
        // ],
      },
      toUploadFiles: [],
      fileCountTimer: null,
      progressModalShow: false,
      uploadProgress: 0,
      fileInfoModal: false,
      selectedFileColumns: [
        {
          title: "key",
          key: "key",
          minWidth: 10,
          width: 110,
        },
        {
          title: "value",
          key: "value",
        },
      ],
      selectedFileData: [],
      panel: null,
      // 单选选中的名称数组
      chooseFilesArray: [],
      // 关于单选多选的按钮
      indeterminate: true,
      checkAll: false,
      shareModal: false,
      editFileModel: false,
      userResourceList: [],
      selectedFilesToShare: [],
      ops: {
        bar: {
          background: "#808695",
        },
      },
      contentHeight: 100,
      copyFileModal: false,
      copyFilePrivacy: "private",
      selectedFile: {},
      delCount: 0,
      putFileInfo: {},
      tempLoginModal: false,
      dataSever: "",
      studentUpload: false,
      folderLock: false,
      selectInfo: {},
      previewType: "",
      filePreviewModal: false,
      scoreModal: false,
      scoreReview: "",
      scoreLevel: "",
      txtReloadFinished: false,
      participants: [],
      getParticipantsFinished: false,
      page: 0,

      pageStorage: [],
    };
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.dataSever = this.$store.getters.dataSever;
    this.classId = window.location.href.split("/classInfo?id=")[1].split("&content")[0];
    this.initSize();
    this.getResList();
    this.roleIdentity();
    window.addEventListener("resize", this.initSize);
  },
  beforeDestroy: function () {
    window.removeEventListener("resize", this.initSize);
  },
  methods: {
    async changepage(index) {
      this.currentPage = index;
      this.currentFolder.folders = [];
      this.currentFolder.files = [];
      let temp = "";
      if (this.folderIdStack.length == 0) {
        temp = this.rootFolderPath;
      } else {
        temp = this.folderIdStack[0];
      }
      let reqInfo = {
        asc: false,
        page: index - 1,
        pageSize: 18,
      };
      console.log(temp);
      //  console.log(this.dataCount);

      // console.log(reqInfo.page);
      //正常的进入文件夹翻页
      let that = this;
      if (this.folderIdStack.length !== 0) {
        let that = this;
        try {
          // console.log(reqInfo);
          let res = await post(
            "/visualResourceLibrary/res/resource/browse/" + temp,
            reqInfo
          );
          // console.log(reqInfo);
          // console.log(res);
          //上线部署后，文件出现溢出情况，后一页的文件在前一页同样出现，但数据库中的文件只有一个。
          //返回数据溢出，暂时找不到原因，先slice前18个。
          let resList = res.data.data.content.slice(0, 18);
          that.dataCount = res.data.data.total;

          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.currentFolder.files.push(resList[i]);
              } else {
                that.currentFolder.folders.push(resList[i]);
              }
            }
          }
          that.currentFolderNum =
            that.currentFolder.folders.length + that.currentFolder.files.length;
        } catch (e) {
          console.log(e);
        }
      } else {
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/browse/" + this.classId,
            reqInfo
          );
          console.log(res);
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;

          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.currentFolder.files.push(resList[i]);
              } else {
                that.currentFolder.folders.push(resList[i]);
              }
            }
          }

          console.log(that.currentPage);
          that.currentFolderNum =
            that.currentFolder.folders.length + that.currentFolder.files.length;
        } catch (e) {
          console.log(e);
        }
      }
    },
    changeLoginModal(status) {
      this.tempLoginModal = status;
    },
    async getAllResList() {
      let reqInfo = {
        asc: false,
        page: 0,
        pageSize: 600,
      };
      this.folderStack = [{ uid: 0, name: "Home" }]
      this.currentFolder.folders = [];
      this.currentFolder.files = [];
      let that = this;
      try {
        let res = await post(
          "/visualResourceLibrary/res/resource/browse/" + this.classId,
          reqInfo
        );
        let resList = res.data.data.content;
        that.dataCount = res.data.data.total;
        console.log(that.dataCount);
        if (resList.length > 0) {
          for (let i = 0; i < resList.length; i++) {
            if (
              resList[i].type &&
              resList[i].type != null &&
              resList[i].type != undefined &&
              resList[i].type != ""
            ) {
              that.currentFolder.files.push(resList[i]);
            } else {
              that.currentFolder.folders.push(resList[i]);
            }
          }
        }
        that.currentFolderNum =
          that.currentFolder.folders.length + that.currentFolder.files.length;
        that.searchFinished = false;
        that.inputSearchText = "";
      } catch (e) {
        console.log(e);
      }
    },
    async getResList() {
      let reqInfo = {
        asc: false,
        page: 0,
        pageSize: 18,
      };
      this.folderStack = [{ uid: 0, name: "Home" }]
      this.currentFolder.folders = [];
      this.currentFolder.files = [];
      let that = this;
      try {
        let res = await post(
          "/visualResourceLibrary/res/resource/browse/" + this.classId,
          reqInfo
        );
        let resList = res.data.data.content;
        that.dataCount = res.data.data.total;
        console.log(that.dataCount);
        if (resList.length > 0) {
          for (let i = 0; i < resList.length; i++) {
            if (
              resList[i].type &&
              resList[i].type != null &&
              resList[i].type != undefined &&
              resList[i].type != ""
            ) {
              that.currentFolder.files.push(resList[i]);
            } else {
              that.currentFolder.folders.push(resList[i]);
            }
          }
        }
        that.currentFolderNum =
          that.currentFolder.folders.length + that.currentFolder.files.length;
        that.searchFinished = false;
        that.inputSearchText = "";
        // 获取boxImg高度
        setTimeout(() => {
          let boxImgList = document.getElementsByClassName("fileImg");
          let folderCardList = document.getElementsByClassName("folderCard");
          // console.log(boxImgList[0].clientHeight);
          this.boxImgSize = boxImgList[0].clientHeight;
          this.folderCardHeight = folderCardList[0].clientHeight;
          this.folderCardWidth = folderCardList[0].clientWidth;
          this.waiting = true;
        }, 10);
        // let rootRes = res.data.data;
        // this.resToCurrentFolder(rootRes);
        this.indeterminate = false;
        this.checkAll = false;
      } catch (e) {
        console.log(e);
      }
    },
    initSize() {
      this.contentHeight = window.innerHeight - 330;
    },
    roleIdentity() {
      this.userRole = this.userInfo.role;
    },
    //工具方法，资源list填充currentFolder
    resToCurrentFolder(rootRes) {
      this.currentFolder.folders = [];
      this.currentFolder.files = [];
      for (let i = 0; i < rootRes.total; i++) {
        if (
          rootRes.content[i].type &&
          rootRes.content[i].type != null &&
          rootRes.content[i].type != undefined &&
          rootRes.content[i].type != ""
        ) {
          this.currentFolder.files.push(rootRes.content[i]);
        } else {
          this.currentFolder.folders.push(rootRes.content[i]);
        }
      }
      // console.log(this.currentFolder);
    },
    enterFolder(currentFolder) {
      this.chooseFilesArray = [];
      this.checkAll = false;
      this.indeterminate = false;
      this.folderIdStack.unshift(currentFolder.id);
      this.changeFolder(currentFolder, "enter");
    },
    backforeFolder() {
      this.chooseFilesArray = [];
      this.checkAll = false;
      this.indeterminate = false;

      if (this.folderStack.length != 1) {
        //folderStack 倒数第二个就是其的父文件夹
        this.folderIdStack.splice(0, 1);
        console.log(this.folderStack.length);

        this.changeFolder(this.folderStack[this.folderStack.length - 2], "back");
      } else {
        this.$Message.warning("This is the root folder.");
      }
    },
    switchFolder(folder, index) {
      this.delCount = this.folderStack.length - index - 1;
      this.folderIdStack.splice(0, this.delCount);

      this.changeFolder(folder, "switch");
    },
    async changeFolder(folder, operationType) {
      // 清空当前页面文件
      this.currentFolder.folders = [];
      this.currentFolder.files = [];
      let temp = "";
      if (this.folderIdStack.length == 0) {
        temp = this.classId;
      } else {
        temp = this.folderIdStack[0];
      }
      
      // console.log("paths: " + temp);
      let reqInfo = {
        asc: false,
        page: 0,
        pageSize: 18,
      };
      if(this.thumbnailShow == false){
      
        reqInfo.pageSize = 600;
        
        };
      // reqInfo.page=this.page;
      // console.log(reqInfo.page);
      // console.log("paths: " + temp.toString());

      // let res = await post(
      //   "/visualResourceLibrary/res/resource/browse/" + temp,
      //   reqInfo
      // );

      // console.log(res);
      // this.resToCurrentFolder(res.data.data);
      if (folder.studentUpload != undefined && folder.studentUpload != null) {
        this.studentUpload = folder.studentUpload;
        this.updateClassTaskLock(temp); //更新任务锁
      } else {
        this.studentUpload = false;
      }
      if (operationType == "enter") {
        this.folderStack.push({ uid: folder.id, name: folder.name });
        let that = this;
        console.log(reqInfo.page);
        console.log(this.currentPage);
        // this.currentPage = reqInfo.page + 1;
        // console.log(this.currentPage);
        this.pageStorage.push(this.currentPage);
        // console.log(this.pageStorage);

        // console.log(this.pageStorage);
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/browse/" + temp,
            reqInfo
          );
          // console.log(res);
          this.currentPage = 1;
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.currentFolder.files.push(resList[i]);
              } else {
                that.currentFolder.folders.push(resList[i]);
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
        // console.log(this.currentFolder);
      } else if (operationType == "back") {
        this.folderStack.pop();

        reqInfo.page = this.pageStorage[this.pageStorage.length - 1] - 1;
        console.log(reqInfo.page);
        this.currentPage = reqInfo.page + 1;
        this.pageStorage.pop();
        let that = this;
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/browse/" + temp,
            reqInfo
          );
          
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.currentFolder.files.push(resList[i]);
              } else {
                that.currentFolder.folders.push(resList[i]);
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
      } else if (operationType == "switch") {
        for (let i = 0; i < this.delCount; i++) {
          this.folderStack.pop();
          this.pageStorage.pop();
        }
        reqInfo.page = 0;
        this.currentPage = 1;
        console.log(this.pageStorage);
        console.log(reqInfo.page);
        let that = this;
        try {
          let res = await post(
            "/visualResourceLibrary/res/resource/browse/" + temp,
            reqInfo
          );
          // console.log(res);
          let resList = res.data.data.content;
          that.dataCount = res.data.data.total;
          if (resList.length > 0) {
            for (let i = 0; i < resList.length; i++) {
              if (
                resList[i].type &&
                resList[i].type != null &&
                resList[i].type != undefined &&
                resList[i].type != ""
              ) {
                that.currentFolder.files.push(resList[i]);
              } else {
                that.currentFolder.folders.push(resList[i]);
              }
            }
          }
        } catch (e) {
          console.log(e);
        }
      }

      this.currentFolderNum =
        this.currentFolder.folders.length + this.currentFolder.files.length;
    },
    async updateClassTaskLock(temp) {
      let res = await get("/visualResourceLibrary/class/task/byId/" + temp);
      this.folderLock = res.data.data.lock;
      // console.log(res);
    },
    getFileInfo(file) {
      if (this.userRole == "admin" || this.userRole == "teacher" || file.uploaderId == this.userInfo.userId) {
        this.selectedFileData = [
          {
            key: "文件名",
            value: file.name + "." + file.suffix,
          },
          {
            key: "文件描述",
            value: file.description,
          },
          {
            key: "文件大小",
            value: this.$options.filters["filterSizeType"](file.fileSize),
          },
          {
            key: "上传者",
            value: file.uploaderName,
          },
          {
            key: "上传时间",
            value: this.$options.filters["filterTimeStyle"](file.createTime),
          },
          {
            key: "得分",
            value: file.scoreLevel,
          },
          {
            key: "评阅意见",
            value: file.scoreReview,
          },
        ];
      } else {
        this.selectedFileData = [
          {
            key: "文件名",
            value: file.name + "." + file.suffix,
          },
          {
            key: "文件描述",
            value: file.description,
          },
          {
            key: "文件大小",
            value: this.$options.filters["filterSizeType"](file.fileSize),
          },
          {
            key: "上传者",
            value: file.uploaderName,
          },
          {
            key: "上传时间",
            value: this.$options.filters["filterTimeStyle"](file.createTime),
          },
        ];
      }
      this.selectInfo = file;
      this.fileInfoModal = true;
    },
    addFolderModalShow() {
      this.newValidate.setName = "";
      this.newFolderModal = true;
    },
    addFolder(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.commitAddFolder();
        }
      });
    },
    async commitAddFolder() {
      let pathArray = this.folderIdStack;
      let parent = "";
      if (pathArray.length == 0) {
        parent = this.classId;
      } else {
        parent = pathArray[0];
      }
      let formData = new FormData();
      formData.append("folderName", this.newValidate.setName);
      formData.append("parent", parent);
      try {
        let res = await post("/visualResourceLibrary/class/res/addFolder", formData);
        this.currentFolder.folders.push(res.data.data);
        this.newFolderModal = false;
        // console.log(res);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async deleteFolder(folder) {
      if (confirm("Are you sure to delete this folder?")) {
        let folderId = folder.id;
        try {
          let res = await del("/visualResourceLibrary/class/res/delFolder/" + folderId);
          //删除用于显示的数据中对应的内容
          for (let i = 0; i < this.currentFolder.folders.length; i++) {
            if (this.currentFolder.folders[i].id == folderId) {
              this.currentFolder.folders.splice(i, 1);
              break;
            }
          }
          // console.log(res);
        } catch (e) {
          this.$Message.error("修改失败");
          console.log(e);
        }
      }
    },
    renameFolderModalShow(folder) {
      this.renameForeInfo = folder;
      this.renameValidate.newName = "";
      this.renameFolderModal = true;
    },
    renameFolder(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.commitRenameFolder();
        }
      });
    },
    async commitRenameFolder() {
      let folderId = this.renameForeInfo.id;
      let newFolderName = this.renameValidate.newName;
      let temp = this.folderIdStack;
      let parent = "";
      if (temp.length == 0) {
        parent = this.classId;
      } else {
        parent = temp[0];
      }
      let formData = new FormData();
      formData.append("parent", parent);
      formData.append("folderId", folderId);
      formData.append("newFolderName", newFolderName);
      try {
        let res = await post("/visualResourceLibrary/class/res/updateFolder", formData);
        let newNameFolder = {
          id: folderId,
          name: newFolderName,
          folder: true,
        };
        for (var i = 0; i < this.currentFolder.folders.length; i++) {
          if (this.currentFolder.folders[i].id == folderId) {
            this.currentFolder.folders.splice(i, 1, newNameFolder);
            break;
          }
        }
        this.renameFolderModal = false;
        // console.log(res);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    uploadModalShow() {
      this.uploadValidate = {
        privacy: "private",
        type: "data",
        description: "",
        format: "",
        scale: "",
        reference: "",
        unit: "",
        concept: "",
      };
      this.toUploadFiles = [];
      this.uploadModal = true;
    },
    // uploadModalBigFileShow() {
     
    //   this.toUploadFiles = [];
    //   this.uploadModalBigFile = true;
    // },
    async getClassMember() {
      if (this.activityInfo.members != null && this.activityInfo.members != undefined) {
        try {
          let res = await get(
            "/visualResourceLibrary/class/member/" + this.activityInfo.members.toString()
          );
          // this.classTaskList = res.data.data;
          this.participants = res.data.data;
          this.getParticipantsFinished = true;
          // console.log(res);
        } catch (e) {
          this.$Message.error("修改失败");
          console.log(e);
        }
      }
    },
    getMockData() {
      let mockData = [];
      let list = this.participants;
      for (let i = 0; i < list.length; i++) {
        mockData.push({
          key: i.toString(),
          label: list[i].name,
          description: list[i].userId,
          disabled: false,
        });
      }
      return mockData;
    },
    getTargetKeys() {
      return this.getMockData()
        .filter(() => Math.random() * 2 > 1)
        .map((item) => item.key);
    },
    flashMemberRender(item) {
      return item.label;
    },
    flashMemberHandleChange(newTargetKeys, direction, moveKeys) {
      // console.log(newTargetKeys);
      // console.log(direction);
      // console.log(moveKeys);
      this.flashMemberTargetKeys = newTargetKeys;
    },
    flashModalShow() {
      this.getClassMember();
      let that = this;
      setTimeout(function () {
        that.flashMemberList = that.getMockData();
        // that.flashMemberTargetKeys = that.getTargetKeys();
        // this.flashMemberList = [];
        that.flashModal = true;
      }, 1000);
    },
    flashMemberUpload() {
      let list = [];
      for (let i = 0; i < this.flashMemberTargetKeys.length; i++) {
        list.push(this.participants[this.flashMemberTargetKeys[i]].userId);
      }
      this.commitFlashMember(list);
    },
    async commitFlashMember(list) {
      let pathArray = this.folderIdStack;
      let parent = "";
      if (pathArray.length == 0) {
        parent = this.classId;
      } else {
        parent = pathArray[0];
      }
      if (list != null && list != undefined && list.length > 0) {
        try {
          let res = await get(
            "/visualResourceLibrary/class/flashMember/" + list.toString() + "/" + parent
          );
          // this.classTaskList = res.data.data;
          // console.log(res);
          for (let i = 0; i < res.data.data.length; i++) {
            this.currentFolder.folders.push(res.data.data[i]);
          }
          this.flashModal = false;
        } catch (e) {
          this.$Message.error("修改失败");
          console.log(e);
        }
      } else {
        this.$Message.error("成员列表为空，请检查是否添加成功");
      }
    },
    gatherFile(file) {
      let that = this;
      if (that.toUploadFiles.length >= 5) {
        if (this.fileCountTimer != null) {
          clearTimeout(this.fileCountTimer);
        }
        this.fileCountTimer = setTimeout(() => {
          this.$Message.info("最多只能上传5个文件");
        }, 500);
      } else {
        var fileSize = file.size;
        if (fileSize < 1024) {
          file.fileSize = fileSize + "b";
        } else if (fileSize < 1024 * 1024) {
          file.fileSize = Math.round((fileSize / 1024) * 100) / 100 + "Kb";
        } else {
          file.fileSize = Math.round((fileSize / (1024 * 1024)) * 100) / 100 + "Mb";
        }
        that.toUploadFiles.push(file);
      }
      return false;
    },
    delFileList(index) {
      this.toUploadFiles.splice(index, 1);
    },
    folderUpload(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.commitUpload();
        }
      });
    },
    async commitUpload() {
      let uploadFiles = this.toUploadFiles;
      if (uploadFiles.length > 0) {
        this.uploadModal = false;
        let formData = new FormData();
        for (let i = 0; i < uploadFiles.length; i++) {
          formData.append("file", uploadFiles[i]);
        }
        let temp = "";
        if (this.folderIdStack.length == 0) {
          temp = this.classId;
        } else {
          temp = this.folderIdStack[0];
        }
        formData.append("description", this.uploadValidate.description);
        formData.append("type", "Reference");
        formData.append("folderId", temp);
        this.progressModalShow = true;
        try {
          let res = await post("/visualResourceLibrary/res", formData);
          // console.log(res);
          this.$Notice.info({
            title: "上传结果",
            desc:
              "失败： " +
              (res.data.data.failed.length + res.data.data.sizeOver.length) +
              ", 成功： " +
              res.data.data.uploaded.length,
          });
          for (let i = 0; i < res.data.data.uploaded.length; i++) {
            this.currentFolder.files.push(res.data.data.uploaded[i]);
          }
          this.uploadProgress = 100;
          this.progressModalShow = false;
          this.uploadProgress = 0;
        } catch (e) {
          this.$Message.error("修改失败");
          this.progressModalShow = false;
          this.uploadProgress = 0;
          console.log(e);
        }
      } else {
        this.$Message.warning("File is not existing.");
        this.progressModalShow = false;
        this.uploadProgress = 0;
      }
    },
    // async submitFile() {
    //   // 将已经上传至chunk区的文件或压缩包进行保存
    //   let uploaderRes = this.uploaderRes;
    //   if (uploaderRes.code == 0) {
    //     //上传成功，可以下一步保存
    //     let formData = new FormData();
    //     formData.append("filePath", uploaderRes.data.path);
    //     let temp = "";
    //     if (this.folderIdStack.length == 0) {
    //       temp = "3";
    //     } else {
    //       temp = this.folderIdStack[0];
    //     }
    //     formData.append("type",  "Reference");
    //     formData.append("name", uploaderRes.data.name);
    //     formData.append("description", this.fileDescription);
    //     formData.append("folderId", temp);
    //     try {
    //       let res = await post("/visualResourceLibrary/res/uploadBig", formData);
    //       // console.log(res);
    //       this.$Message.success("上传成功");
    //       this.switchFolder(
    //         this.folderStack[this.folderStack.length - 1],
    //         this.folderIdStack.length
    //       );
    //     } catch (e) {
    //       this.$Message.error("上传失败");
    //       console.log(e);
    //     }
    //   } else {
    //     //上传失败，请重新上传
    //     this.$Message.error("上传失败，请重新上传");
    //   }
    // },

    showScoreModal() {
      let parentsDom = document.getElementsByClassName("previewBoxModal")[0];
      let modalDonList = document.getElementsByClassName("ivu-modal");
      let targetDom;
      for (let i = 0; i < modalDonList.length; i++) {
        if (this.isChildOf(modalDonList[i], parentsDom)) {
          targetDom = modalDonList[i];
        }
      }
      if (!this.scoreModal) {
        this.scoreModal = true;
        if (this.selectInfo.scoreLevel != "") {
          this.scoreReview = this.selectInfo.scoreReview;
          this.scoreLevel = this.selectInfo.scoreLevel;
        }
        targetDom.style.width = "1400px";
      } else {
        this.scoreModal = false;
        targetDom.style.width = "1100px";
      }
      // console.log(document.getElementsByClassName("ivu-modal"));
    },
    isChildOf(child, parent) {
      if (child && parent) {
        let parentNode = child.parentNode;
        while (parentNode) {
          if (parent === parentNode) {
            return true;
          }
          parentNode = parentNode.parentNode;
        }
      }
      return false;
    },
    filePreview() {
      this.previewType = "";
      this.previewUrl = "";
      let fileInfo = this.selectInfo;
      this.fileInfoModal = false;
      this.filePreviewModal = true;
      let url = this.dataSever;
      let resStr = fileInfo.url;
      // console.log(fileInfo);
      if (resStr.indexOf("resRepository") != -1) {
        resStr = "resRepository" + resStr.split("resRepository")[1];
        url = url + resStr;
      } else {
        return -1;
      }
      let name = fileInfo.name + "." + fileInfo.suffix;
      if (/\.(doc|docx|xls|xlsx|ppt|pptx)$/.test(name.toLowerCase())) {
        this.previewType = "office";
        let Base64 = require("js-base64").Base64;
        // this.previewUrl = "http://221.226.60.2:8082/onlinePreview?url=" + url;
        this.previewUrl =
          "http://1.13.163.229:8012/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(url));
      } else if (/\.(mp4)$/.test(name.toLowerCase())) {
        this.previewType = "video";
        this.playerOptions.sources[0].src = url;
        this.videoUrlFinished = true;
      } else if (/\.(pdf|json|gif|jpg|png)$/.test(name.toLowerCase())) {
        this.previewType = "normal";
        this.previewUrl = url;
      } else if (/\.(txt|csv|html|md|py|js)$/.test(name.toLowerCase())) {
        this.previewType = "txt";
        this.txtReloadFinished = false;
        let value = this.getTxtFile(url);
        value.then((result) => {
          const that = this;
          var reader = new FileReader();
          reader.readAsText(result);
          reader.onload = function (event) {
            that.previewUrl = reader.result;
            // console.log(reader.result);
            that.txtReloadFinished = true;
          };
        });
      } else {
        this.$Notice.error({
          title: "Open failed",
          desc: "Sorry. Unsupported file format.",
        });
        this.filePreviewModal = false;
        return false;
      }
    },
    closeFilePreview() {
      //如果有评阅信息，则向后台请求
      if (this.scoreModal && this.scoreLevel != "") {
        this.commitScore();
      }
      this.filePreviewModal = false;
      // this.filePreviewModal = false;
      if (this.previewType == "video") {
        this.videoUrlFinished = false;
      }
    },
    async commitScore() {
      let fileInfo = this.selectInfo;
      let formData = new FormData();
      formData.append("id", fileInfo.id);
      formData.append("scoreReview", this.scoreReview);
      formData.append("scoreLevel", this.scoreLevel);
      try {
        let res = await post("/visualResourceLibrary/res/score", formData);
        this.scoreReview = "";
        this.scoreLevel = "";
        this.showScoreModal();
        for (let i = 0; i < this.currentFolder.files.length; i++) {
          if (this.currentFolder.files[i].id == fileInfo.id) {
            this.currentFolder.files.splice(i, 1, res.data.data);
          }
        }
        // console.log(res);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    getTxtFile(url) {
      return new Promise((resolve, reject) => {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader("Accept", "text/html");
        xhr.responseType = "blob";
        xhr.onload = () => {
          blob = xhr.response;
          let tempFile = new File([blob], "tempTxt", { type: "text/html" });
          resolve(tempFile);
        };
        xhr.onerror = (e) => {
          reject(e);
        };
        xhr.send();
      });
    },
    async fileDelete(fileInfo) {
      // console.log(fileInfo);
      if (confirm("Are you sure to delete ?")) {
        let fileId = fileInfo.id;
        let temp = "";
        if (this.folderIdStack.length == 0) {
          temp = this.classId;
        } else {
          temp = this.folderIdStack[0];
        }
        let that = this;
        try {
          let res = await get("/visualResourceLibrary/res/delete/" + temp + "/" + fileId);
          // console.log(res);
          for (let i = 0; i < that.currentFolder.files.length; i++) {
            if (that.currentFolder.files[i].id == fileId) {
              that.currentFolder.files.splice(i, 1);
            }
          }
        } catch (e) {
          console.log(e);
        }
      }
    },
    download(blobUrl) {
      const a = document.createElement("a");
      a.style.display = "none";
      a.download = "package.zip";
      a.href = blobUrl;
      a.click();
      a.remove();
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;
      if (this.checkAll) {
        this.currentFolder.files.forEach((item) => {
          this.chooseFilesArray.push(item.id);
        });
      } else {
        this.chooseFilesArray = [];
      }
    },
    checkAllGroupChange(data) {
      if (data.length == this.currentFolder.files.length) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
    },
    downloadSelectFile() {
      let chooseFileUrls = this.chooseFilesArray;
      // console.log(this.chooseFilesArray)
      let temp = [];
      if (chooseFileUrls.length != 0) {
        for (let i = 0; i < chooseFileUrls.length; i++) {
          temp.push(chooseFileUrls[i].split("/data/")[1]);
        }
        window.open(
          `http://${this.$store.state.DataServer}/batchData?oids=` + temp.toString()
        );
      }
    },
    shareModalShow() {
      this.shareModal = true;
      this.axios
        .get("/GeoProblemSolving/res/file/all")
        .then((res) => {
          if (res.data == "Offline") {
            this.$store.commit("userLogout");
            this.tempLoginModal = true;
          } else if (res.data != "None" && res.data != "Fail") {
            this.userResourceList = res.data.data;
            this.shareModal = true;
          } else if (res.data == "None") {
            this.userResourceList = [];
          }
        })
        .catch((err) => {
          console.log(err.data);
        });
    },
    closeshareModel() {
      this.shareModal = false;
    },
    shareFile() {
      let addFileList = this.selectedFilesToShare;
      let tempPath = this.folderIdStack;
      if (tempPath.length == 0) {
        tempPath = ["0"];
      }
      this.axios
        .get(
          "/GeoProblemSolving/rip/shareToProject/" +
            this.activityInfo.aid +
            "/" +
            addFileList.toString() +
            "/" +
            tempPath.toString()
        )
        .then((res) => {
          this.shareModal = false;
          if (res.data == "Offline") {
            this.$store.commit("userLogout");
            this.tempLoginModal = true;
          } else if (res.data.code == 0) {
            let sharedFile = res.data.data;
            for (let i = 0; i < sharedFile.length; i++) {
              this.currentFolder.files.push(sharedFile[i]);
            }
            this.$Message.success("Shared file success!");
            this.selectedFilesToShare = [];
          } else {
            this.$Message.error("Shared file fail!");
          }
        })
        .catch((err) => {
          this.$Message.error("Shared file fail!");
        });
    },
    fileDownload(fileInfo) {
      // window.open(this.dataSever + fileInfo.url);
      try {
        window.open("/visualResourceLibrary/res/down/" + fileInfo.id);
      } catch (e) {
        console.log(e);
      }
    },
    fileEditModelShow(fileInfo) {
      this.putFileInfo = fileInfo;
      this.editFileValidate.name = fileInfo.name;
      this.editFileValidate.type = fileInfo.type;
      this.editFileValidate.description = fileInfo.description;
      this.editFileModel = true;
    },
    editFileInfo(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.editFileValidate.name.indexOf("/") != -1) {
            this.$Message.warning("不可以使用'/'符号命名！");
          } else {
            this.commitUpdateResFile();
          }
        }
      });
    },
    async commitUpdateResFile() {
      let formData = new FormData();
      formData.append("resId", this.putFileInfo.id);
      formData.append("name", this.editFileValidate.name);
      formData.append("description", this.editFileValidate.description);
      formData.append("type", this.editFileValidate.type);
      try {
        let res = await post("/visualResourceLibrary/res/update", formData);
        this.putFileInfo.name = this.editFileValidate.name;
        this.putFileInfo.type = this.editFileValidate.type;
        this.putFileInfo.description = this.editFileValidate.description;
        for (var i = 0; i < this.currentFolder.files.length; i++) {
          if (this.currentFolder.files[i].id == this.putFileInfo.id) {
            this.currentFolder.files.splice(i, 1, this.putFileInfo);
            break;
          }
        }
        this.editFileModel = false;
      } catch (e) {
        console.log(e);
      }
    },
    canBeShare(fileId) {
      //判断项目中是否由此文件，如果有，则不能共享
      let result = true;
      for (let i = 0; i < this.currentFolder.files.length; i++) {
        if (this.currentFolder.files[i].uid == fileId) {
          result = false;
        }
      }
      return result;
    },
    showCopyFileModel(file) {
      this.copyFileModal = true;
      this.copyFilePrivacy = "private";
      this.selectedFile = file;
    },
    copyFileToCenter() {
      this.$Spin.show();
      this.selectedFile.privacy = this.copyFilePrivacy;
      this.axios
        .post("/GeoProblemSolving/res/file/copyToCenter", this.selectedFile)
        .then((res) => {
          this.$Spin.hide();
          this.copyFileModal = false;
          if (res.data.code == 0) {
            this.$Message.success("Copy file success.");
          } else {
            this.$Message.warning(res.data.data);
          }
        })
        .catch((err) => {
          this.$Message.error("Copy file fail.");
        });
    },
    turn2Folder(str) {
      setTimeout(()=> {
      let folderId = str;
      for (let i = 0; i < this.currentFolder.folders.length; i++) {
        if ((folderId == this.currentFolder.folders[i].id)) {
          this.enterFolder(this.currentFolder.folders[i]);
        }
      }
      },500)
    },
    // //大文件上传所需
    // fileAdded(file) {
    //   //选择文件后暂停文件上传，上传时手动启动
    //   file.pause();
    // },
    // onFileError(file) {
    //   console.log("error", file);
    // },
    // onFileSuccess(rootFile, file, response, chunk) {
    //   this.uploaderRes = JSON.parse(response);
    // },
  },
  filters: {
    filterSizeType(value) {
      // 无法处理 i逼近与.99的情况，如1.99.   把精确的位数增加一位，问题初步解决
      if (value === 0) return "0 B";
      let k = 1024;
      let sizes = ["B", "KB", "MB", "GB"];
      let i = Math.floor(Math.log(value) / Math.log(k));
      return (value / Math.pow(k, i)).toPrecision(4) + " " + sizes[i];
    },
    filterTimeStyle(str) {
      return (str = new Date(str).toLocaleString());
      // if (str != null) {
      //   let result = str.split(".")[0];
      //   return result.replace("T", " ");
      // }
      // return str;
    },
  },
};
</script>
